package com.example.its2021606134chh.TrafficViolationModule;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.ETCModule.Cars;
import com.example.its2021606134chh.ETCModule.CarsRViewAdapter;
import com.example.its2021606134chh.ETCModule.ETC_Car_Recharge;
import com.example.its2021606134chh.ETCModule.MySQLiteOpenHelper;
import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.LoginModule.GuideActivity;
import com.example.its2021606134chh.LoginModule.WelcomeActivity;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TrafficViolationSearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TrafficViolationSearchFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private EditText edtTVSearCarNum;
    private Button btnTVSearSearch;
    CarSQLiteOpenHelper openHelper;
    SQLiteDatabase database;
    public static SharedPreferences sp;

    public TrafficViolationSearchFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TrafficViolationSearchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TrafficViolationSearchFragment newInstance(String param1, String param2) {
        TrafficViolationSearchFragment fragment = new TrafficViolationSearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_traffic_violation_search, container, false);
        openHelper = new CarSQLiteOpenHelper(getContext(), "CarPeccancy.db", null, 1);

//        首次打开此页面，创建数据库存储所有车辆违章记录。
        sp = getActivity().getSharedPreferences("CarPeccancy", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        int x = sp.getInt("CarPeccancy",1);
        if (x == 1)
        {
            x++;
            editor.putInt("CarPeccancy",x);
            editor.commit();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            CarPeccancy car = gson.fromJson(json, CarPeccancy.class);
                            List<CarPeccancy.ROWSDETAILBean> Temp = car.getROWS_DETAIL();
                            for (int i = 0; i < Temp.size(); i++) {
                                ContentValues values = new ContentValues();
                                values.put("id", Temp.get(i).getId());
                                values.put("carnumber", Temp.get(i).getCarnumber());
                                values.put("pdatetime", Temp.get(i).getPdatetime());
                                values.put("paddr", Temp.get(i).getPaddr());
                                database = openHelper.getWritableDatabase();
                                database.insert("carpeccancy", null, values);
                                database.close();
                            }
                            Log.i("TAG", "" + Temp.size());
                        }
                    }, "get_all_car_peccancy", new String[]{"UserName"}, "user1");
                }
            }).start();
        }


        edtTVSearCarNum = (EditText) view.findViewById(R.id.edtTVSearCarNum);
        edtTVSearCarNum.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

        btnTVSearSearch = (Button) view.findViewById(R.id.btnTVSearSearch);

//        通过对数据库遍历查找指定车牌号，若存在则结束循环并跳转具体页。
        btnTVSearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sCarNum = "鲁" + edtTVSearCarNum.getText().toString().trim();
                database = openHelper.getReadableDatabase();
                try (Cursor cursor = database.query("carpeccancy", null, null, null, null, null, null)) {
                    if (cursor.moveToFirst()) {
                        do {
                            int id = cursor.getInt(0);
                            String carnumber = cursor.getString(1);
                            String pdatetime = cursor.getString(2);
                            String paddr = cursor.getString(3);
                            if (carnumber.equals(sCarNum)) {
                                Log.i("TAG", "id: " + id + ", carnumber: " + carnumber + ", pdatetime: " + pdatetime + ", paddr: " + paddr);
                                Intent intent = new Intent(getActivity(), TVSearchResultsActivity.class);
                                intent.putExtra("carnumber", sCarNum);
                                startActivity(intent);
                                break;
                            }
                        } while (cursor.moveToNext());
                    }
                } catch (SQLException ignored) {
                    Toast.makeText(getActivity(), "没有查询到" + sCarNum + "车的违章数据！", Toast.LENGTH_SHORT).show();
                } finally {
                    database.close();
                }
            }
        });
        // Inflate the layout for this fragment
        return view;
    }

    private void initView() {

    }
}